package com.ww.exercise.coroutine.easy.q8

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

fun main() {
    // 测试不加锁的情况
    val unsafeResult = testCounter(useLock = false)
    println("不加锁的结果：$unsafeResult（预期10000）")

    // 测试加锁的情况
    val safeResult = testCounter(useLock = true)
    println("加锁的结果：$safeResult（预期10000）")
}

fun testCounter(useLock: Boolean): Int = runBlocking(Dispatchers.Default) {
    var counter = 0
    val mutex = Mutex() // 创建互斥锁
    val coroutineCount = 10 // 协程数量
    val incrementsPerCoroutine = 1000 // 每个协程的递增次数

    // 启动多个协程
    val jobs = List(coroutineCount) {
        launch {
            repeat(incrementsPerCoroutine) {
                if (useLock) {
                    mutex.withLock {
                        counter++
                    }
                } else {
                    counter++
                }
            }
        }
    }

    // 等待所有协程完成
    jobs.joinAll()

    counter// 返回最终结果
}